package org.scohen.juploadr.util;

import java.util.ArrayList;
import java.util.List;
/**
 * A simple decorator that changes a list into a stack
 * @author steve
 *
 */
public class StackListDecorator<E> {
    private List<E> list;
    private int maxSize = -1;

    public StackListDecorator(int maxSize) {
        this(new ArrayList<E>(maxSize), maxSize);
    }

    public StackListDecorator(List<E> l, int maxSize) {
        this.list = l;
        this.maxSize =maxSize;
    }

    public void push(E o) {
        list.add(list.size(), o);
        trimList();
    }

    public E pop() {
        E rv = null;
        if (!isEmpty()) {
            rv = list.remove(list.size() - 1);
        }
        trimList();
        return rv;
    }

    public boolean isEmpty() {
        trimList();
        return list.size() == 0;
    }

    private void trimList() {
        if (list.size() > 0 &&   list.size() > maxSize) {
            list.remove(0);
        }
    }

    public static void main(String[] args) {
        StackListDecorator<Integer> sd = new StackListDecorator<Integer>(6);
        sd.push(new Integer(1));
        sd.push(new Integer(2));
        sd.push(new Integer(3));
        sd.push(new Integer(4));
        sd.push(new Integer(5));
        sd.push(new Integer(6));

        System.out.println(sd.isEmpty());
        System.out.println(sd.pop());
        System.out.println(sd.isEmpty());
        System.out.println(sd.pop());
        System.out.println(sd.isEmpty());
        System.out.println(sd.pop());
        System.out.println(sd.isEmpty());
        System.out.println(sd.pop());
        System.out.println(sd.isEmpty());
        System.out.println(sd.pop());
        System.out.println(sd.isEmpty());
        System.out.println(sd.pop());
        System.out.println(sd.isEmpty());
    }
}
